$(document).ready(function() {
  let data = {
    initData:window.Telegram.WebApp.initData,
    initDataUnsafe:window.Telegram.WebApp.initDataUnsafe
  }

  function getCodeImg(){
    $.ajax({
      url: "/api/captchaImage",
      type: 'GET',
      beforeSend: function (xhr) {
        xhr.setRequestHeader('isToken', 'false');
      },
      success: function(res) {
        $('img').attr('src', "data:image/gif;base64,"+res.img);
        data.uuid = res.uuid;
      },
      error: function(xhr, status, error) {
        // 处理错误
      }
    });
  }
  //加载验证码
  getCodeImg();
  $("body").css('height',window.Telegram.WebApp.viewportStableHeight-100)
  // 验证码图片点击事件，用于刷新验证码
  $('#captcha-image').click(function() {
    getCodeImg();
  });

  // 登录按钮点击事件
  $('#login-btn').click(function() {
    //window.Telegram.WebApp.close()
    // 获取输入的验证码
    var captcha = $('#captcha').val();
    //验证码必填
    if(!captcha){
      $('#error-message').text("请输入验证码");
      return;
    }
    data.code = captcha;
    // 在这里执行登录逻辑，包括验证码的验证
    // 假设的验证码验证，实际中应该在服务器端验证

    $('#login-btn').attr("disabled", true);
    $.ajax({
      url: "/api/bot/verify/newChat",
      type: 'POST',
      data:JSON.stringify(data),
      contentType:"application/json; charset=utf-8",
      dataType:"json",
      beforeSend: function (xhr) {
        xhr.setRequestHeader('isToken', 'false');
      },
      success: function(res) {
        $('#error-message').text(res.msg);
        if(res.code==200){
          let t = res.data;
          let interval = setInterval(function(){
            $('#error-message').text("验证通过,"+t+"秒后自动返回");
            t--
            if(t<0){
              clearInterval(interval);
              window.Telegram.WebApp.close()
            }
          },1000)
       }else if(res.code==403){
          //无权限操作
        }else{
          $('#login-btn').attr("disabled", false);
          getCodeImg()
        }
      },
      error: function(xhr, status, error) {
        $('#login-btn').attr("disabled", false);
        // 处理错误
        getCodeImg()
      }
    });
  });
});
